package com.proton.carepatchtemp.base;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.apkfuns.logutils.LogUtils;
import com.baidu.mobstat.StatService;
import com.proton.carepatchtemp.utils.eventbus.MainBusListener;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public abstract class BaseFragment extends Fragment implements MainBusListener {

    public BaseFragment() {
        // Required empty public constructor
        initBus();
    }

    public abstract void dealEvent(MainEvent event);

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getName()); //统计页面，"MainScreen"为页面名称，可自定义
        StatService.onPageStart(getActivity(), this.getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getName());
        StatService.onPageEnd(getActivity(), this.getClass().getSimpleName());
    }

    public void initBus() {
       /* if(new EventBus().isRegistered(this)){
            EventBus.getDefault().register(BaseFragment.this);
        }*/
        EventBus.getDefault().register(BaseFragment.this);
    }

    public boolean canDeal(MainEvent event) {
        return event != null && getActivity() != null && !getActivity().isFinishing();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dealOnEvent(MainEvent event) {
        if (canDeal(event)) {
            try {
                dealEvent(event);
            } catch (Throwable e) {
                LogUtils.e(e);
            }
        }
    }

    public void unRegisterEventBus() {
        EventBus.getDefault().unregister(BaseFragment.this);
    }

    protected String getName() {
        return getClass().getSimpleName();
    }
}
